<!-- 本示例未包含完整css，获取外链css请参考上文，在hello uni-app项目中查看 -->
<template>
	<div>
		<movable-area scale-area class="movable-area" v-if="imageSrc" :style="{ top: areaTop+'px',width:CLIP_WIDTH_RPX+'rpx',height:CLIP_HEIGHT_RPX+'rpx',left:(750 - CLIP_WIDTH_RPX) / 2+'rpx'}">
			<movable-view scale inertia damping="1000" direction="all" scale-min="1" :style="{width: initialWidth+'px',height:initialHeight+'px'}"
			 :x="initialX" :y="initialY" @change="onChange" @scale="onScale">
				<image class="image" :src="imageSrc" />
			</movable-view>
		</movable-area>


		<view class="clip-box" :style="{ top: areaTop+'px',width:CLIP_WIDTH_RPX+'rpx',height:CLIP_HEIGHT_RPX+'rpx',left:(750 - CLIP_WIDTH_RPX) / 2+'rpx'}" />
		<view class="bottom-btns">
			<button size="mini" @tap="onClickCancel">取消</button>
			<button size="mini" @tap="onClickConfirm">完成</button>
		</view>
		<canvas v-if="canvasWidth" canvas-id="shareCardCanvas" type="2d" class="canvas" :style="{width: canvasWidth+'px',height:canvasHeight+'px'}"></canvas>

	</div>
</template>

<script>
	import {
		CLIP_WIDTH_RPX,
		CLIP_HEIGHT_RPX,
		IMG_IPLOAD_ADDRESS
	} from './constant'
	import {
		loadCanvasImage
	} from './util'
	export default {
		data() {
			return {
				CLIP_WIDTH_RPX: CLIP_WIDTH_RPX,
				CLIP_HEIGHT_RPX: CLIP_HEIGHT_RPX,
				dpr: 2,
				// 用户选择的图片的地址
				imageSrc: '',
				// movable-area top 的值
				areaTop: 0,
				initialWidth: 0,
				initialHeight: 0,
				initialX: 0,
				initialY: 0,
				initialScale: 1,
				clipWidth: 0,
				clipHeight: 0,
				x: 0,
				y: 0,
				scale: 1,
				// 存下这两个值是因为在 wxml 中有用到，来设置 canvas 宽高了
				canvasWidth: 0,
				canvasHeight: 0
			}
		},
		onLoad(options) {
			let that = this
			const imageSrc = options.url
			const {
				windowWidth,
				windowHeight,
				pixelRatio
			} = wx.getSystemInfoSync()
			// 裁剪框配置值是 rpx ，计算出对应的 px 值
			const clipWidth = (windowWidth / 750) * that.CLIP_WIDTH_RPX
			const clipHeight = (windowWidth / 750) * that.CLIP_HEIGHT_RPX
			// 计算出裁剪框应该距离顶部的值，以便定位
			const areaTop = (windowHeight - clipHeight) / 2
			wx.getImageInfo({
				src: imageSrc,
				success: (res) => {
					const {
						width,
						height
					} = res
					// 在知道图片本身的宽高后，一开始需要缩放一下图片使得图片的宽或者高等于裁剪框尺寸
					const scale = Math.max(clipWidth / width, clipHeight / height)
					const initialWidth = width * scale
					const initialHeight = height * scale
					// that.dpr = pixelRatio,
					that.imageSrc = imageSrc,
						that.areaTop = areaTop,
						that.initialWidth = initialWidth,
						that.initialHeight = initialHeight,
						that.initialX = (clipWidth - initialWidth) / 2,
						that.initialY = (clipHeight - initialHeight) / 2,
						that.initialScale = scale,
						that.clipWidth = clipWidth,
						that.clipHeight = clipHeight
				},
			})
		},
		methods: {
			onChange(e) {
				const {
					x,
					y
				} = e.detail
				this.x = x
				this.y = y
			},
			onScale(e) {
				const {
					x,
					y,
					scale
				} = e.detail
				this.x = x
				this.y = y
			},
			onClickCancel: function(e) {
				wx.navigateBack()
			},

			onClickConfirm: function(e) {
				uni.showLoading({
					title: '裁剪中...',
					mask: true
				})
				const {
					dpr,
					imageSrc,
					x,
					y,
					initialScale,
					scale,
					clipWidth,
					clipHeight,
				} = this
				const totalScale = scale * initialScale
				const sx = -x / totalScale
				const sy = -y / totalScale
				const canvasWidth = clipWidth / totalScale
				const canvasHeight = clipHeight / totalScale

				this.canvasWidth = canvasWidth
				this.canvasHeight = canvasHeight
				const query = uni.createSelectorQuery()
				setTimeout(function() {
					query.select('.canvas').fields({
						node: true,
						size: true
					})
					query.exec((res) => {
						console.log('sssss', res)
						const canvas = res[0].node
						const context = canvas.getContext('2d')
						canvas.width = res[0].width * dpr
						canvas.height = res[0].height * dpr
						context.scale(dpr, dpr)
						// 在 canvas 上把原图上裁剪框对应的部分给画上去，然后导出即可
						loadCanvasImage(canvas, imageSrc).then((img) => {
							context.drawImage(
								img,
								sx,
								sy,
								canvasWidth,
								canvasHeight,
								0,
								0,
								canvasWidth,
								canvasHeight
							)
							wx.canvasToTempFilePath({
								fileType: 'jpg',
								canvas,
								success: (res) => {
									// TODO: 这里在实际项目中应该是调用 wx.uploadFile 来上传采集后图片
									/**
									 * 这里可以直接调用服务器进行裁剪后的图片上传，
									 * 也可以直接获取到临时文件路径 res.tempFilePath
									 */
									console.log('res.tempFilePath', res.tempFilePath)

									uni.setStorageSync('fileUrl', res.tempFilePath)
									uni.navigateBack()

									// uni.uploadFile({
									// 	fileType: "image",
									// 	url: IMG_IPLOAD_ADDRESS + '?bizType=wxphoto',
									// 	filePath: res.tempFilePath,
									// 	name: 'file',
									// 	success(res) {
									// 		uni.hideLoading()
									// 		let item = JSON.parse(res.data)
									// 		uni.setStorageSync('fileUrl', item.data.fileUrl)
									// 		uni.navigateBack()
									// 	}
									// })


									// let pages = getCurrentPages();//当前页面
									// let prevPage = pages[pages.length-2];//上一页面
									// prevPage.setData({//直接给上移页面赋值
									//   item: e.currentTarget.dataset.item,
									//   selAddress:'yes'
									// });
									// wx.navigateBack({//返回
									//   delta:1
									// })
								},
								fail(e) {
									console.log('fail', e)
									uni.hideLoading()
								},
							})
						})
					})
				}, 1000)

			},
		}
	}
</script>
<style scoped lang=scss>
	@import "index";
</style>
